/**
 *      example of use :
 *              app.ajax({
 *                      method: 'POST',
 *                      url: 'ololo',
 *                      data: 'o=0&lo=L0',
 *                      success: function(response){...},
 *                      loading: function(response){...},//useful for creating comet apps 
 *                      complete: function(){...}
 *              });
 */
(function () {
  var namespace = namespace || 'app';
  if(typeof (window[namespace]) === 'undefined') {
    return;
  }
  var method;
  var url;
  var data;
  var success;
  var loading;
  var complete;
  var transport = (function () {
    if(window.XMLHttpRequest) {
      return new XMLHttpRequest();
    } else return new ActiveXObject('Microsoft.XMLHTTP');
  }())
  var init = function (_) {
      method = _.method || 'GET';
      url = _.url || '';
      data = _.data || '';
      success = _.success ||
      function () {};
      loading = _.loading ||
      function () {};
      complete = _.complete ||
      function () {};
    }
  var proceed = function (options) {
      if(!transport)
        return;
      options = options || {};
      var ar = ['method', 'url', 'data', 'success', 'loading', 'complete'];
      for(var i = 0; i < ar.length; i++) {
        if(!options.hasOwnProperty(ar[i])) {
          options[ar[i]] = '';
        }
      }
      init(options);
      if(method == 'GET') {
        transport.open(method, url + data, true);
        transport.send(null);
      } else if(method == 'POST') {
        /*transport.open(method, url, true);
        transport.setRequestHeader("Content-type",
                                   "application/x-www-form-urlencoded");
        transport.send(data);*/
        transport.open(method, url + data, true);
        transport.send(null);
      } else {
        return;
      }
      transport.onreadystatechange = function () {
        switch(transport.readyState) {
        case 3:
          if(transport.status >= 200 && transport.status < 400) {
            loading(transport.responseText);
          }
          break;
        case 4:
          if(transport.status >= 200 && transport.status < 400) {
            success(transport.responseText);
            complete();
          }
          break;
        }
      }
    }
  window[namespace].ajax = proceed;
}());
